home *** CD-ROM | disk | FTP | other *** search
/ PC World 2007 September / PCWorld_2007-09_cd.bin / system / ntfs / ntfsundelete.exe / {app} / threading.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2007-02-05  |  24KB  |  865 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """Thread module emulating a subset of Java's threading model."""
  5. import sys as _sys
  6.  
  7. try:
  8.     import thread
  9. except ImportError:
  10.     del _sys.modules[__name__]
  11.     raise 
  12.  
  13. from time import time as _time, sleep as _sleep
  14. from traceback import format_exc as _format_exc
  15. from collections import deque
  16. __all__ = [
  17.     'activeCount',
  18.     'Condition',
  19.     'currentThread',
  20.     'enumerate',
  21.     'Event',
  22.     'Lock',
  23.     'RLock',
  24.     'Semaphore',
  25.     'BoundedSemaphore',
  26.     'Thread',
  27.     'Timer',
  28.     'setprofile',
  29.     'settrace',
  30.     'local']
  31. _start_new_thread = thread.start_new_thread
  32. _allocate_lock = thread.allocate_lock
  33. _get_ident = thread.get_ident
  34. ThreadError = thread.error
  35. del thread
  36. _VERBOSE = False
  37. if __debug__:
  38.     
  39.     class _Verbose(object):
  40.         
  41.         def __init__(self, verbose = None):
  42.             if verbose is None:
  43.                 verbose = _VERBOSE
  44.             
  45.             self._Verbose__verbose = verbose
  46.  
  47.         
  48.         def _note(self, format, *args):
  49.             if self._Verbose__verbose:
  50.                 format = format % args
  51.                 format = '%s: %s\n' % (currentThread().getName(), format)
  52.                 _sys.stderr.write(format)
  53.             
  54.  
  55.  
  56. else:
  57.     
  58.     class _Verbose(object):
  59.         
  60.         def __init__(self, verbose = None):
  61.             pass
  62.  
  63.         
  64.         def _note(self, *args):
  65.             pass
  66.  
  67.  
  68. _profile_hook = None
  69. _trace_hook = None
  70.  
  71. def setprofile(func):
  72.     global _profile_hook
  73.     _profile_hook = func
  74.  
  75.  
  76. def settrace(func):
  77.     global _trace_hook
  78.     _trace_hook = func
  79.  
  80. Lock = _allocate_lock
  81.  
  82. def RLock(*args, **kwargs):
  83.     return _RLock(*args, **kwargs)
  84.  
  85.  
  86. class _RLock(_Verbose):
  87.     
  88.     def __init__(self, verbose = None):
  89.         _Verbose.__init__(self, verbose)
  90.         self._RLock__block = _allocate_lock()
  91.         self._RLock__owner = None
  92.         self._RLock__count = 0
  93.  
  94.     
  95.     def __repr__(self):
  96.         if self._RLock__owner:
  97.             pass
  98.         return '<%s(%s, %d)>' % (self.__class__.__name__, self._RLock__owner.getName(), self._RLock__count)
  99.  
  100.     
  101.     def acquire(self, blocking = 1):
  102.         me = currentThread()
  103.         if self._RLock__owner is me:
  104.             self._RLock__count = self._RLock__count + 1
  105.             if __debug__:
  106.                 self._note('%s.acquire(%s): recursive success', self, blocking)
  107.             
  108.             return 1
  109.         
  110.         rc = self._RLock__block.acquire(blocking)
  111.         if rc:
  112.             self._RLock__owner = me
  113.             self._RLock__count = 1
  114.             if __debug__:
  115.                 self._note('%s.acquire(%s): initial succes', self, blocking)
  116.             
  117.         elif __debug__:
  118.             self._note('%s.acquire(%s): failure', self, blocking)
  119.         
  120.         return rc
  121.  
  122.     
  123.     def release(self):
  124.         me = currentThread()
  125.         if not self._RLock__owner is me:
  126.             raise AssertionError, 'release() of un-acquire()d lock'
  127.         self._RLock__count = count = self._RLock__count - 1
  128.         if not count:
  129.             self._RLock__owner = None
  130.             self._RLock__block.release()
  131.             if __debug__:
  132.                 self._note('%s.release(): final release', self)
  133.             
  134.         elif __debug__:
  135.             self._note('%s.release(): non-final release', self)
  136.         
  137.  
  138.     
  139.     def _acquire_restore(self, .2):
  140.         (count, owner) = .2
  141.         self._RLock__block.acquire()
  142.         self._RLock__count = count
  143.         self._RLock__owner = owner
  144.         if __debug__:
  145.             self._note('%s._acquire_restore()', self)
  146.         
  147.  
  148.     
  149.     def _release_save(self):
  150.         if __debug__:
  151.             self._note('%s._release_save()', self)
  152.         
  153.         count = self._RLock__count
  154.         self._RLock__count = 0
  155.         owner = self._RLock__owner
  156.         self._RLock__owner = None
  157.         self._RLock__block.release()
  158.         return (count, owner)
  159.  
  160.     
  161.     def _is_owned(self):
  162.         return self._RLock__owner is currentThread()
  163.  
  164.  
  165.  
  166. def Condition(*args, **kwargs):
  167.     return _Condition(*args, **kwargs)
  168.  
  169.  
  170. class _Condition(_Verbose):
  171.     
  172.     def __init__(self, lock = None, verbose = None):
  173.         _Verbose.__init__(self, verbose)
  174.         if lock is None:
  175.             lock = RLock()
  176.         
  177.         self._Condition__lock = lock
  178.         self.acquire = lock.acquire
  179.         self.release = lock.release
  180.         
  181.         try:
  182.             self._release_save = lock._release_save
  183.         except AttributeError:
  184.             pass
  185.  
  186.         
  187.         try:
  188.             self._acquire_restore = lock._acquire_restore
  189.         except AttributeError:
  190.             pass
  191.  
  192.         
  193.         try:
  194.             self._is_owned = lock._is_owned
  195.         except AttributeError:
  196.             pass
  197.  
  198.         self._Condition__waiters = []
  199.  
  200.     
  201.     def __repr__(self):
  202.         return '<Condition(%s, %d)>' % (self._Condition__lock, len(self._Condition__waiters))
  203.  
  204.     
  205.     def _release_save(self):
  206.         self._Condition__lock.release()
  207.  
  208.     
  209.     def _acquire_restore(self, x):
  210.         self._Condition__lock.acquire()
  211.  
  212.     
  213.     def _is_owned(self):
  214.         if self._Condition__lock.acquire(0):
  215.             self._Condition__lock.release()
  216.             return False
  217.         else:
  218.             return True
  219.  
  220.     
  221.     def wait(self, timeout = None):
  222.         if not self._is_owned():
  223.             raise AssertionError, 'wait() of un-acquire()d lock'
  224.         waiter = _allocate_lock()
  225.         waiter.acquire()
  226.         self._Condition__waiters.append(waiter)
  227.         saved_state = self._release_save()
  228.         
  229.         try:
  230.             if timeout is None:
  231.                 waiter.acquire()
  232.                 if __debug__:
  233.                     self._note('%s.wait(): got it', self)
  234.                 
  235.             else:
  236.                 endtime = _time() + timeout
  237.                 delay = 0.00050000000000000001
  238.                 while True:
  239.                     gotit = waiter.acquire(0)
  240.                     if gotit:
  241.                         break
  242.                     
  243.                     remaining = endtime - _time()
  244.                     if remaining <= 0:
  245.                         break
  246.                     
  247.                     delay = min(delay * 2, remaining, 0.050000000000000003)
  248.                     _sleep(delay)
  249.                 if not gotit:
  250.                     if __debug__:
  251.                         self._note('%s.wait(%s): timed out', self, timeout)
  252.                     
  253.                     
  254.                     try:
  255.                         self._Condition__waiters.remove(waiter)
  256.                     except ValueError:
  257.                         pass
  258.                     except:
  259.                         None<EXCEPTION MATCH>ValueError
  260.                     
  261.  
  262.                 None<EXCEPTION MATCH>ValueError
  263.                 if __debug__:
  264.                     self._note('%s.wait(%s): got it', self, timeout)
  265.                 self._acquire_restore(saved_state)
  266.                 return None
  267.  
  268.  
  269.     
  270.     def notify(self, n = 1):
  271.         if not self._is_owned():
  272.             raise AssertionError, 'notify() of un-acquire()d lock'
  273.         _Condition__waiters = self._Condition__waiters
  274.         waiters = _Condition__waiters[:n]
  275.         if not waiters:
  276.             if __debug__:
  277.                 self._note('%s.notify(): no waiters', self)
  278.             
  279.             return None
  280.         
  281.         if not n != 1 or 's':
  282.             pass
  283.         self._note('%s.notify(): notifying %d waiter%s', self, n, '')
  284.         for waiter in waiters:
  285.             waiter.release()
  286.             
  287.             try:
  288.                 _Condition__waiters.remove(waiter)
  289.             continue
  290.             except ValueError:
  291.                 continue
  292.             
  293.  
  294.         
  295.  
  296.     
  297.     def notifyAll(self):
  298.         self.notify(len(self._Condition__waiters))
  299.  
  300.  
  301.  
  302. def Semaphore(*args, **kwargs):
  303.     return _Semaphore(*args, **kwargs)
  304.  
  305.  
  306. class _Semaphore(_Verbose):
  307.     
  308.     def __init__(self, value = 1, verbose = None):
  309.         if not value >= 0:
  310.             raise AssertionError, 'Semaphore initial value must be >= 0'
  311.         _Verbose.__init__(self, verbose)
  312.         self._Semaphore__cond = Condition(Lock())
  313.         self._Semaphore__value = value
  314.  
  315.     
  316.     def acquire(self, blocking = 1):
  317.         rc = False
  318.         self._Semaphore__cond.acquire()
  319.         while self._Semaphore__value == 0:
  320.             if not blocking:
  321.                 break
  322.             
  323.             if __debug__:
  324.                 self._note('%s.acquire(%s): blocked waiting, value=%s', self, blocking, self._Semaphore__value)
  325.             
  326.             self._Semaphore__cond.wait()
  327.         self._Semaphore__value = self._Semaphore__value - 1
  328.         if __debug__:
  329.             self._note('%s.acquire: success, value=%s', self, self._Semaphore__value)
  330.         
  331.         rc = True
  332.         self._Semaphore__cond.release()
  333.         return rc
  334.  
  335.     
  336.     def release(self):
  337.         self._Semaphore__cond.acquire()
  338.         self._Semaphore__value = self._Semaphore__value + 1
  339.         if __debug__:
  340.             self._note('%s.release: success, value=%s', self, self._Semaphore__value)
  341.         
  342.         self._Semaphore__cond.notify()
  343.         self._Semaphore__cond.release()
  344.  
  345.  
  346.  
  347. def BoundedSemaphore(*args, **kwargs):
  348.     return _BoundedSemaphore(*args, **kwargs)
  349.  
  350.  
  351. class _BoundedSemaphore(_Semaphore):
  352.     '''Semaphore that checks that # releases is <= # acquires'''
  353.     
  354.     def __init__(self, value = 1, verbose = None):
  355.         _Semaphore.__init__(self, value, verbose)
  356.         self._initial_value = value
  357.  
  358.     
  359.     def release(self):
  360.         if self._Semaphore__value >= self._initial_value:
  361.             raise ValueError, 'Semaphore released too many times'
  362.         
  363.         return _Semaphore.release(self)
  364.  
  365.  
  366.  
  367. def Event(*args, **kwargs):
  368.     return _Event(*args, **kwargs)
  369.  
  370.  
  371. class _Event(_Verbose):
  372.     
  373.     def __init__(self, verbose = None):
  374.         _Verbose.__init__(self, verbose)
  375.         self._Event__cond = Condition(Lock())
  376.         self._Event__flag = False
  377.  
  378.     
  379.     def isSet(self):
  380.         return self._Event__flag
  381.  
  382.     
  383.     def set(self):
  384.         self._Event__cond.acquire()
  385.         
  386.         try:
  387.             self._Event__flag = True
  388.             self._Event__cond.notifyAll()
  389.         finally:
  390.             self._Event__cond.release()
  391.  
  392.  
  393.     
  394.     def clear(self):
  395.         self._Event__cond.acquire()
  396.         
  397.         try:
  398.             self._Event__flag = False
  399.         finally:
  400.             self._Event__cond.release()
  401.  
  402.  
  403.     
  404.     def wait(self, timeout = None):
  405.         self._Event__cond.acquire()
  406.         
  407.         try:
  408.             if not self._Event__flag:
  409.                 self._Event__cond.wait(timeout)
  410.         finally:
  411.             self._Event__cond.release()
  412.  
  413.  
  414.  
  415. _counter = 0
  416.  
  417. def _newname(template = 'Thread-%d'):
  418.     global _counter
  419.     _counter = _counter + 1
  420.     return template % _counter
  421.  
  422. _active_limbo_lock = _allocate_lock()
  423. _active = { }
  424. _limbo = { }
  425.  
  426. class Thread(_Verbose):
  427.     __initialized = False
  428.     __exc_info = _sys.exc_info
  429.     
  430.     def __init__(self, group = None, target = None, name = None, args = (), kwargs = { }, verbose = None):
  431.         if not group is None:
  432.             raise AssertionError, 'group argument must be None for now'
  433.         _Verbose.__init__(self, verbose)
  434.         self._Thread__target = target
  435.         if not name:
  436.             pass
  437.         self._Thread__name = str(_newname())
  438.         self._Thread__args = args
  439.         self._Thread__kwargs = kwargs
  440.         self._Thread__daemonic = self._set_daemon()
  441.         self._Thread__started = False
  442.         self._Thread__stopped = False
  443.         self._Thread__block = Condition(Lock())
  444.         self._Thread__initialized = True
  445.         self._Thread__stderr = _sys.stderr
  446.  
  447.     
  448.     def _set_daemon(self):
  449.         return currentThread().isDaemon()
  450.  
  451.     
  452.     def __repr__(self):
  453.         if not self._Thread__initialized:
  454.             raise AssertionError, 'Thread.__init__() was not called'
  455.         status = 'initial'
  456.         if self._Thread__started:
  457.             status = 'started'
  458.         
  459.         if self._Thread__stopped:
  460.             status = 'stopped'
  461.         
  462.         if self._Thread__daemonic:
  463.             status = status + ' daemon'
  464.         
  465.         return '<%s(%s, %s)>' % (self.__class__.__name__, self._Thread__name, status)
  466.  
  467.     
  468.     def start(self):
  469.         if not self._Thread__initialized:
  470.             raise AssertionError, 'Thread.__init__() not called'
  471.         if not not (self._Thread__started):
  472.             raise AssertionError, 'thread already started'
  473.         if __debug__:
  474.             self._note('%s.start(): starting thread', self)
  475.         
  476.         _active_limbo_lock.acquire()
  477.         _limbo[self] = self
  478.         _active_limbo_lock.release()
  479.         _start_new_thread(self._Thread__bootstrap, ())
  480.         self._Thread__started = True
  481.         _sleep(9.9999999999999995e-007)
  482.  
  483.     
  484.     def run(self):
  485.         if self._Thread__target:
  486.             self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
  487.         
  488.  
  489.     
  490.     def __bootstrap(self):
  491.         
  492.         try:
  493.             self._Thread__started = True
  494.             _active_limbo_lock.acquire()
  495.             _active[_get_ident()] = self
  496.             del _limbo[self]
  497.             _active_limbo_lock.release()
  498.             if __debug__:
  499.                 self._note('%s.__bootstrap(): thread started', self)
  500.             
  501.             if _trace_hook:
  502.                 self._note('%s.__bootstrap(): registering trace hook', self)
  503.                 _sys.settrace(_trace_hook)
  504.             
  505.             if _profile_hook:
  506.                 self._note('%s.__bootstrap(): registering profile hook', self)
  507.                 _sys.setprofile(_profile_hook)
  508.             
  509.             
  510.             try:
  511.                 self.run()
  512.             except SystemExit:
  513.                 if __debug__:
  514.                     self._note('%s.__bootstrap(): raised SystemExit', self)
  515.                 
  516.             except:
  517.                 __debug__
  518.                 if __debug__:
  519.                     self._note('%s.__bootstrap(): unhandled exception', self)
  520.                 
  521.                 if _sys:
  522.                     _sys.stderr.write('Exception in thread %s:\n%s\n' % (self.getName(), _format_exc()))
  523.                 else:
  524.                     (exc_type, exc_value, exc_tb) = self._Thread__exc_info()
  525.                     
  526.                     try:
  527.                         print >>self._Thread__stderr, 'Exception in thread ' + self.getName() + ' (most likely raised during interpreter shutdown):'
  528.                         print >>self._Thread__stderr, 'Traceback (most recent call last):'
  529.                         while exc_tb:
  530.                             print >>self._Thread__stderr, '  File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)
  531.                             exc_tb = exc_tb.tb_next
  532.                         print >>self._Thread__stderr, '%s: %s' % (exc_type, exc_value)
  533.                     finally:
  534.                         del exc_type
  535.                         del exc_value
  536.                         del exc_tb
  537.  
  538.  
  539.             if __debug__:
  540.                 self._note('%s.__bootstrap(): normal return', self)
  541.         finally:
  542.             self._Thread__stop()
  543.             
  544.             try:
  545.                 self._Thread__delete()
  546.             except:
  547.                 pass
  548.  
  549.  
  550.  
  551.     
  552.     def __stop(self):
  553.         self._Thread__block.acquire()
  554.         self._Thread__stopped = True
  555.         self._Thread__block.notifyAll()
  556.         self._Thread__block.release()
  557.  
  558.     
  559.     def __delete(self):
  560.         '''Remove current thread from the dict of currently running threads.'''
  561.         _active_limbo_lock.acquire()
  562.         
  563.         try:
  564.             del _active[_get_ident()]
  565.         except KeyError:
  566.             if 'dummy_threading' not in _sys.modules:
  567.                 raise 
  568.             
  569.         except:
  570.             'dummy_threading' not in _sys.modules
  571.         finally:
  572.             _active_limbo_lock.release()
  573.  
  574.  
  575.     
  576.     def join(self, timeout = None):
  577.         if not self._Thread__initialized:
  578.             raise AssertionError, 'Thread.__init__() not called'
  579.         if not self._Thread__started:
  580.             raise AssertionError, 'cannot join thread before it is started'
  581.         if not self is not currentThread():
  582.             raise AssertionError, 'cannot join current thread'
  583.         if __debug__:
  584.             if not self._Thread__stopped:
  585.                 self._note('%s.join(): waiting until thread stops', self)
  586.             
  587.         
  588.         self._Thread__block.acquire()
  589.         if timeout is None:
  590.             while not self._Thread__stopped:
  591.                 self._Thread__block.wait()
  592.             if __debug__:
  593.                 self._note('%s.join(): thread stopped', self)
  594.             
  595.         else:
  596.             deadline = _time() + timeout
  597.             while not self._Thread__stopped:
  598.                 delay = deadline - _time()
  599.                 if delay <= 0:
  600.                     if __debug__:
  601.                         self._note('%s.join(): timed out', self)
  602.                     
  603.                     break
  604.                 
  605.                 self._Thread__block.wait(delay)
  606.             if __debug__:
  607.                 self._note('%s.join(): thread stopped', self)
  608.             
  609.         self._Thread__block.release()
  610.  
  611.     
  612.     def getName(self):
  613.         if not self._Thread__initialized:
  614.             raise AssertionError, 'Thread.__init__() not called'
  615.         return self._Thread__name
  616.  
  617.     
  618.     def setName(self, name):
  619.         if not self._Thread__initialized:
  620.             raise AssertionError, 'Thread.__init__() not called'
  621.         self._Thread__name = str(name)
  622.  
  623.     
  624.     def isAlive(self):
  625.         return None if not self._Thread__initialized else not (self._Thread__stopped)
  626.  
  627.     
  628.     def isDaemon(self):
  629.         if not self._Thread__initialized:
  630.             raise AssertionError, 'Thread.__init__() not called'
  631.         return self._Thread__daemonic
  632.  
  633.     
  634.     def setDaemon(self, daemonic):
  635.         if not self._Thread__initialized:
  636.             raise AssertionError, 'Thread.__init__() not called'
  637.         if not not (self._Thread__started):
  638.             raise AssertionError, 'cannot set daemon status of active thread'
  639.         self._Thread__daemonic = daemonic
  640.  
  641.  
  642.  
  643. def Timer(*args, **kwargs):
  644.     return _Timer(*args, **kwargs)
  645.  
  646.  
  647. class _Timer(Thread):
  648.     """Call a function after a specified number of seconds:
  649.  
  650.     t = Timer(30.0, f, args=[], kwargs={})
  651.     t.start()
  652.     t.cancel() # stop the timer's action if it's still waiting
  653.     """
  654.     
  655.     def __init__(self, interval, function, args = [], kwargs = { }):
  656.         Thread.__init__(self)
  657.         self.interval = interval
  658.         self.function = function
  659.         self.args = args
  660.         self.kwargs = kwargs
  661.         self.finished = Event()
  662.  
  663.     
  664.     def cancel(self):
  665.         """Stop the timer if it hasn't finished yet"""
  666.         self.finished.set()
  667.  
  668.     
  669.     def run(self):
  670.         self.finished.wait(self.interval)
  671.         if not self.finished.isSet():
  672.             self.function(*self.args, **self.kwargs)
  673.         
  674.         self.finished.set()
  675.  
  676.  
  677.  
  678. class _MainThread(Thread):
  679.     
  680.     def __init__(self):
  681.         Thread.__init__(self, name = 'MainThread')
  682.         self._Thread__started = True
  683.         _active_limbo_lock.acquire()
  684.         _active[_get_ident()] = self
  685.         _active_limbo_lock.release()
  686.         import atexit as atexit
  687.         atexit.register(self._MainThread__exitfunc)
  688.  
  689.     
  690.     def _set_daemon(self):
  691.         return False
  692.  
  693.     
  694.     def _MainThread__exitfunc(self):
  695.         self._Thread__stop()
  696.         t = _pickSomeNonDaemonThread()
  697.         if t:
  698.             if __debug__:
  699.                 self._note('%s: waiting for other threads', self)
  700.             
  701.         
  702.         while t:
  703.             t.join()
  704.             t = _pickSomeNonDaemonThread()
  705.         if __debug__:
  706.             self._note('%s: exiting', self)
  707.         
  708.         self._Thread__delete()
  709.  
  710.  
  711.  
  712. def _pickSomeNonDaemonThread():
  713.     for t in enumerate():
  714.         if not t.isDaemon() and t.isAlive():
  715.             return t
  716.             continue
  717.     
  718.  
  719.  
  720. class _DummyThread(Thread):
  721.     
  722.     def __init__(self):
  723.         Thread.__init__(self, name = _newname('Dummy-%d'))
  724.         self._Thread__started = True
  725.         _active_limbo_lock.acquire()
  726.         _active[_get_ident()] = self
  727.         _active_limbo_lock.release()
  728.  
  729.     
  730.     def _set_daemon(self):
  731.         return True
  732.  
  733.     
  734.     def join(self, timeout = None):
  735.         if not False:
  736.             raise AssertionError, 'cannot join a dummy thread'
  737.  
  738.  
  739.  
  740. def currentThread():
  741.     
  742.     try:
  743.         return _active[_get_ident()]
  744.     except KeyError:
  745.         return _DummyThread()
  746.  
  747.  
  748.  
  749. def activeCount():
  750.     _active_limbo_lock.acquire()
  751.     count = len(_active) + len(_limbo)
  752.     _active_limbo_lock.release()
  753.     return count
  754.  
  755.  
  756. def enumerate():
  757.     _active_limbo_lock.acquire()
  758.     active = _active.values() + _limbo.values()
  759.     _active_limbo_lock.release()
  760.     return active
  761.  
  762. _MainThread()
  763.  
  764. try:
  765.     from thread import _local as local
  766. except ImportError:
  767.     from _threading_local import local
  768.  
  769.  
  770. def _test():
  771.     
  772.     class BoundedQueue(_Verbose):
  773.         
  774.         def __init__(self, limit):
  775.             _Verbose.__init__(self)
  776.             self.mon = RLock()
  777.             self.rc = Condition(self.mon)
  778.             self.wc = Condition(self.mon)
  779.             self.limit = limit
  780.             self.queue = deque()
  781.  
  782.         
  783.         def put(self, item):
  784.             self.mon.acquire()
  785.             while len(self.queue) >= self.limit:
  786.                 self._note('put(%s): queue full', item)
  787.                 self.wc.wait()
  788.             self.queue.append(item)
  789.             self._note('put(%s): appended, length now %d', item, len(self.queue))
  790.             self.rc.notify()
  791.             self.mon.release()
  792.  
  793.         
  794.         def get(self):
  795.             self.mon.acquire()
  796.             while not self.queue:
  797.                 self._note('get(): queue empty')
  798.                 self.rc.wait()
  799.             item = self.queue.popleft()
  800.             self._note('get(): got %s, %d left', item, len(self.queue))
  801.             self.wc.notify()
  802.             self.mon.release()
  803.             return item
  804.  
  805.  
  806.     
  807.     class ProducerThread(Thread):
  808.         
  809.         def __init__(self, queue, quota):
  810.             Thread.__init__(self, name = 'Producer')
  811.             self.queue = queue
  812.             self.quota = quota
  813.  
  814.         
  815.         def run(self):
  816.             random = random
  817.             import random
  818.             counter = 0
  819.             while counter < self.quota:
  820.                 counter = counter + 1
  821.                 self.queue.put('%s.%d' % (self.getName(), counter))
  822.                 _sleep(random() * 1.0000000000000001e-005)
  823.  
  824.  
  825.     
  826.     class ConsumerThread(Thread):
  827.         
  828.         def __init__(self, queue, count):
  829.             Thread.__init__(self, name = 'Consumer')
  830.             self.queue = queue
  831.             self.count = count
  832.  
  833.         
  834.         def run(self):
  835.             while self.count > 0:
  836.                 item = self.queue.get()
  837.                 print item
  838.                 self.count = self.count - 1
  839.  
  840.  
  841.     NP = 3
  842.     QL = 4
  843.     NI = 5
  844.     Q = BoundedQueue(QL)
  845.     P = []
  846.     for i in range(NP):
  847.         t = ProducerThread(Q, NI)
  848.         t.setName('Producer-%d' % (i + 1))
  849.         P.append(t)
  850.     
  851.     C = ConsumerThread(Q, NI * NP)
  852.     for t in P:
  853.         t.start()
  854.         _sleep(9.9999999999999995e-007)
  855.     
  856.     C.start()
  857.     for t in P:
  858.         t.join()
  859.     
  860.     C.join()
  861.  
  862. if __name__ == '__main__':
  863.     _test()
  864.  
  865.